<template>
  <div class="design-templates">
    <el-card class="templates-card">
      <template #header>
        <div class="card-header">
          <h2>推荐模板</h2>
          <div class="header-controls">
            <el-select v-model="filterSubject" placeholder="学科筛选" clearable>
              <el-option
                v-for="subject in subjects"
                :key="subject"
                :label="subject"
                :value="subject"
              />
            </el-select>
            <el-select v-model="filterGrade" placeholder="年级筛选" clearable>
              <el-option
                v-for="grade in grades"
                :key="grade"
                :label="grade"
                :value="grade"
              />
            </el-select>
            <el-button type="primary" @click="fetchTemplates" :loading="loading">刷新</el-button>
          </div>
        </div>
      </template>
      <div class="templates-list" v-loading="loading">
        <div v-if="templates.length === 0 && !loading" class="empty-tip">
          暂无模板
        </div>
        <div v-for="(template, index) in filteredTemplates" 
             :key="index" 
             class="template-item"
             @click="viewTemplateDetail(template)">
          <div class="template-item-header">
            <span class="template-subject">【{{ template.subject }}】{{ template.grade }}</span>
            <span class="template-time">{{ template.time }}</span>
          </div>
          <div class="template-title">{{ template.title }}</div>
          <div class="template-content">{{ template.content }}</div>
          <div class="template-item-footer">
            <el-tag size="small" type="info">模板</el-tag>
            <div class="template-actions">
              <el-button size="small" type="primary" @click.stop="useTemplate(template)">使用此模板</el-button>
            </div>
          </div>
        </div>
        <div class="bottom-space"></div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/utils/request'
import { User, RefreshRight, View, DocumentCopy } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()
const templates = ref([])
const loading = ref(false)
const filterSubject = ref('')
const filterGrade = ref('')

// 筛选选项
const subjects = ref(['语文', '数学', '英语', '物理', '化学', '生物', '历史', '地理', '政治'])
const grades = ref(['小学一年级', '小学二年级', '小学三年级', '小学四年级', '小学五年级', '小学六年级', 
                   '初一', '初二', '初三', '高一', '高二', '高三'])

// 根据筛选条件过滤模板
const filteredTemplates = computed(() => {
  let result = [...templates.value]
  
  if (filterSubject.value) {
    result = result.filter(item => item.subject === filterSubject.value)
  }
  
  if (filterGrade.value) {
    result = result.filter(item => item.grade === filterGrade.value)
  }
  
  return result
})

// 添加全局样式
const globalStyle = document.createElement('style');
globalStyle.textContent = `
.template-detail-dialog .el-message-box__content {
  max-height: 70vh;
  overflow-y: auto;
}
.template-detail-dialog .el-message-box {
  width: 80%;
  max-width: 600px;
}
.template-detail-dialog .el-message-box__message p {
  margin: 0;
  line-height: 1.6;
}
`;
document.head.appendChild(globalStyle);

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true;
  
  try {
    // 更正API路径
    const response = await axios.get('/api/teaching-plans/templates', {
      params: {
        subject: filterSubject.value,
        grade: filterGrade.value
      }
    });
    
    if (response.data && Array.isArray(response.data)) {
      templates.value = response.data.map(item => ({
        id: item.id,
        subject: item.subject || '未指定',
        grade: item.grade || '未指定',
        title: item.title || '未命名教学计划',
        content: item.content,
        duration: item.duration || 45,
        isTemplate: true,
        time: new Date(item.createTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }));
    } else {
      console.error('响应格式不正确:', response);
      ElMessage.error('获取模板失败：格式不正确');
      templates.value = [];
    }
  } catch (error) {
    console.error('获取模板失败:', error);
    ElMessage.error('获取模板失败，请稍后重试');
    templates.value = [];
  } finally {
    loading.value = false;
  }
}

// 查看模板详情
const viewTemplateDetail = (template) => {
  const contentHtml = template.content ? `<div style="white-space: pre-wrap;">${template.content}</div>` : '无内容';
  
  ElMessageBox.alert(
    `<div style="font-size:15px;line-height:1.6;">
      <div style="margin-bottom:15px;"><strong>标题：</strong>${template.title}</div>
      <div style="margin-bottom:15px;"><strong>内容：</strong>${contentHtml}</div>
      <div style="margin-bottom:8px;"><strong>科目：</strong>${template.subject}</div>
      <div style="margin-bottom:8px;"><strong>年级：</strong>${template.grade}</div>
      <div style="margin-bottom:8px;"><strong>课时：</strong>${template.duration}分钟</div>
      <div><strong>创建时间：</strong>${template.time}</div>
    </div>`,
    '模板详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'template-detail-dialog'
    }
  )
}

// 使用模板
const useTemplate = (template) => {
  // 将模板信息存储到localStorage，以便在NewDesign页面中使用
  localStorage.setItem('selectedTemplate', JSON.stringify({
    id: template.id,
    title: template.title,
    subject: template.subject,
    grade: template.grade,
    content: template.content
  }))
  
  // 提示用户
  ElMessage.success('已选择模板，即将跳转到设计页面')
  
  // 跳转到设计页面
  setTimeout(() => {
    router.push('/design/new')
  }, 1000)
}

onMounted(() => {
  fetchTemplates()
})

const handleRefresh = () => {
  fetchTemplates()
}
</script>

<style scoped>
.design-templates {
  height: 100%;
}

.templates-card {
  height: 100%;
  background-color: #fff;
  border-radius: 8px;
  margin-top: -20px;
  margin-left: -20px;
  margin-right: -20px;
}

.templates-list {
  height: calc(100vh - 190px);
  overflow-y: auto;
  padding: 10px 10px 25px 10px;
}

.template-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.template-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.template-item:last-child {
  margin-bottom: 30px; /* 为最后一项增加额外的底部边距 */
}

.template-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.template-subject {
  font-weight: 600;
  color: #303133;
}

.template-time {
  font-size: 12px;
  color: #909399;
}

.template-title {
  font-weight: 500;
  font-size: 16px;
  margin-bottom: 8px;
  color: #303133;
}

.template-content {
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 12px;
}

.template-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.template-actions {
  display: flex;
  gap: 8px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

/* 添加滚动条样式 */
.templates-list::-webkit-scrollbar {
  width: 6px;
}

.templates-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.templates-list::-webkit-scrollbar-track {
  background-color: transparent;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.bottom-space {
  height: 20px;
}
</style> 